package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.PageBean;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;

import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.util.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;

    @Autowired(required = false)
    private SalesMapper salesMapper;
    /**
     * 订单页分页查询
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public R<PageBean> findOrderPage(int page, int pageSize, String number, String beginTime, String endTime) {
        //1.处理参数
        LocalDateTime orderBeginTime = null;
        LocalDateTime orderEndTime = null;
        if (beginTime!=null&&beginTime!=""){
           orderBeginTime = LocalDateTime.parse(beginTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        if (endTime != null && endTime != ""){
            orderEndTime=LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }


        //2.分页查询
        PageHelper.startPage(page,pageSize);
        List<Orders> ordersList = orderMapper.findOrderPage(number,orderBeginTime,orderEndTime);
        PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);
//        List<OrdersDto> ordersDtoList = new ArrayList<>();
//        for (Orders orders : ordersPageInfo.getList()) {
//            OrdersDto ordersDto = new OrdersDto();
//            BeanUtils.copyProperties(orders,ordersDto);
//
//        }
        return ordersPageInfo!=null?R.success(new PageBean(ordersPageInfo.getList(),ordersPageInfo.getTotal(),pageSize,page)):R.error("查询失败");
    }

    /**
     * 用户中心页
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public R<PageBean> findUserPage(int page, int pageSize,long id) {
        PageHelper.startPage(page,pageSize);
        //查询用户订单
        List<Orders> ordersList = orderMapper.findOrderByUserId(id);
        PageInfo<Orders> ordersPageInfo = new PageInfo<>(ordersList);
        List<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders orders : ordersPageInfo.getList()) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);
            ordersDto.setOrderDetails(orderDetailMapper.findOrderDetailByOrderId(orders.getId()));
            ordersDtoList.add(ordersDto);
        }
        return R.success(new PageBean(ordersDtoList,ordersPageInfo.getTotal(),pageSize,page,ordersPageInfo.getPages()));

    }

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @Transactional
    @Override
    public R<Orders> submitOrder(Orders orders) {


        //在数据库中查询当前用户购物车所有商品
        List<ShoppingCart> cart = shoppingCartMapper.findShoppingCartByUserId(orders.getUserId());
        //查询下单地址
        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        //生成订单id
        Long uuidInOrderId = Long.valueOf(UUIDUtils.getUUIDInOrderId());


        BigDecimal allAmount = new BigDecimal(0);
        for (ShoppingCart shoppingCart : cart) {
            BigDecimal num = new BigDecimal(shoppingCart.getNumber());
            BigDecimal amount = num.multiply(shoppingCart.getAmount());
            allAmount = allAmount.add(amount);
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setOrderId(uuidInOrderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(amount);
            orderDetail.setImage(shoppingCart.getImage());
            //更新购物车数据
            //获取当前年月字符串
            String month = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
            Sales sales = salesMapper.find(shoppingCart, month);
            if (sales!=null){
                //数据不为空直接更新销量
                salesMapper.update(shoppingCart,sales);
            }else {
                //数据为空插入新数据
                salesMapper.insert(shoppingCart,month);
            }


            //插入订单详情
            int orderDetailInsertResult = orderDetailMapper.insert(orderDetail);
        }


        //封装数据
        orders.setId(uuidInOrderId);
        orders.setNumber(UUIDUtils.getUUID());
        orders.setStatus(1);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(allAmount);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
//        生成订单
        int submitResult = orderMapper.insertOrders(orders);

//        清空购物车
        shoppingCartMapper.cleanShoppingCart(orders.getUserId());

        return R.success(orders);
    }

    @Override
    public int updateByWxMap(Map<String, String> map) {
        Orders orders = new Orders();
        orders.setStatus(2);
        orders.setNumber(map.get("out_trade_no"));
        orders.setCheckoutTime(LocalDateTime.now());
        return orderMapper.updateOrderIsPay(orders);
    }

    /**
     * 查询用户byId
     * @param number
     * @return
     */
    @Override
    public Orders findOrderByNumber(String number) {
        return orderMapper.findOrderByNumber(number);
    }
}
